package com.weipeep.oss.sdk;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.weipeep.common.exception.IFastException;
import com.weipeep.common.type.EnumErrorCode;
import com.weipeep.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;

/**
 * <pre>
 * 七牛对象存储服务
 * </pre>
 * 
 * <small> 2018年4月6日 | wangyun</small>
 */
public class AliOSSService {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    String accessUrl;
    String bucketName;
    // 创建OSSClient实例
    OSSClient ossClient ;

    public AliOSSService(String endpoint,String accessKeyId,String accessKeySecret,String accessUrl,String bucketName) {
        this.accessUrl = accessUrl;
        this.bucketName = bucketName;
        ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
    }

    // method

    public String upload(byte[] uploadBytes, String fileName) {
        try {
            PutObjectResult result = ossClient.putObject(bucketName,fileName,new ByteArrayInputStream(uploadBytes));
            log.info("上传成功，url:{}", JSONUtils.beanToJson(result));
            return accessUrl+"/"+fileName;
        } catch (OSSException ex){
            ossClient.shutdown();
            ex.printStackTrace();
            throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
        }
    }

}
